/**
 * Copyright &copy; 2012-2016 <a href="https://www.kaaction.com">KAA</a> All rights reserved All rights reserved.
 */
package com.kaaction.modules.crab.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.kaaction.common.beanvalidator.BeanValidators;
import com.kaaction.common.config.Global;
import com.kaaction.common.persistence.Page;
import com.kaaction.common.utils.DateUtils;
import com.kaaction.common.utils.StringUtils;
import com.kaaction.common.utils.excel.ExportExcel;
import com.kaaction.common.utils.excel.ImportExcel;
import com.kaaction.common.web.BaseController;
import com.kaaction.modules.crab.entity.Order;
import com.kaaction.modules.crab.service.OrderService;
import com.kaaction.modules.crab.utils.KuaiDi100;
import com.kaaction.modules.sys.entity.User;
import com.kaaction.modules.sys.utils.UserUtils;

/**
 * 订单管理Controller
 * @author huanghaiming
 * @version 2017-07-21
 */
@Controller
@RequestMapping(value = "${adminPath}/crab/order")
public class OrderController extends BaseController {

	@Autowired
	private OrderService orderService;
	
	@ModelAttribute
	public Order get(@RequestParam(required=false) String id) {
		Order entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = orderService.get(id);
		}
		if (entity == null){
			entity = new Order();
		}
		return entity;
	}
	
	@RequiresPermissions("crab:order:view")
	@RequestMapping(value = {"list", ""})
	public String list(Order order, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Order> page = orderService.findPage(new Page<Order>(request, response), order); 
		model.addAttribute("page", page);
		return "modules/crab/orderList";
	}

	@RequiresPermissions("crab:order:form")
	@RequestMapping(value = "form")
	public String form(Order order, Model model) {
		model.addAttribute("order", order);
		return "modules/crab/orderForm";
	}

	@RequiresPermissions("crab:order:save")
	@RequestMapping(value = "save")
	public String save(Order order, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, order)){
			return form(order, model);
		}
		orderService.save(order);
		addMessage(redirectAttributes, "保存订单管理成功");
		return "redirect:"+Global.getAdminPath()+"/crab/order/?repage";
	}
	
	@RequiresPermissions("crab:order:delete")
	@RequestMapping(value = "delete")
	public String delete(Order order, RedirectAttributes redirectAttributes) {
		orderService.delete(order);
		addMessage(redirectAttributes, "删除订单管理成功");
		return "redirect:"+Global.getAdminPath()+"/crab/order/?repage";
	}
	
	/**
	 * 导出订单数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("crab:order:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Order order, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "订单数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            List<Order> list = orderService.findOrder(order);
    		new ExportExcel("订单数据", Order.class).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出订单数据失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/crab/order/?repage";
    }
	
	/**
	 * 下载导入订单模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("crab:order:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "订单导入模板.xlsx";
    		List<Order> list = Lists.newArrayList();
    		new ExportExcel("订单数据", Order.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/crab/order/list?repage";
    }

	/**
	 * 导入订单管理数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("crab:order:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			User user = UserUtils.getUser();
			String name = user.getName();
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Order> list = ei.getDataList(Order.class);
			boolean b = true; 
			for (Order order : list){
				try{
					BeanValidators.validateWithException(validator, order);
					String  state = order.getState();
					String  str = "";
					if("未发货".equals(state)){
						str = "0";
					}else if("已发货".equals(state)){
						str = "1";
					}else{
						failureMsg.append("<br/>状态为：未发货或已发货");
						failureNum++;
						b = false;
					}
					if(b){
						order.setState(str);
						orderService.updateOrder(order);
						successNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>登录名 "+name+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>登录名 "+name+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 订单信息，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条订单信息"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入订单信息失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/crab/order/list?repage";
    }
	
	@RequiresPermissions("crab:order:orderLogisticsForm")
	@RequestMapping(value = "orderLogisticsForm")
	public String orderLogisticsForm(Order order, Model model) {
		String  url = KuaiDi100.searchkuaiDiInfo("1949fc1aa47e87f1", "shunfeng", order.getExpressNum());
		order.setLogisticsInformationUrl(url);
		model.addAttribute("order", order);
		return "modules/crab/orderLogisticsForm";
	}
	
}